package io.dy.main;

import io.dy.model.Hero;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author : dmj
 * @date: 2024/12/18 9:21 上午
 * @description: 函数聚合(化简)
 */
public class StreamReduce {

    List<Hero> list = Arrays.asList(
            new Hero("杨过",100),
            new Hero("小龙女",98),
            new Hero("金轮法王",98),
            new Hero("郭靖",97),
            new Hero("李莫愁",95),
            new Hero("黄蓉",95),
            new Hero("H",95),
            new Hero("黄药师",99),
            new Hero("老顽童",99),
            new Hero("一灯大师",99)
    );

    /**
     * reduce操作
     */
    @Test
    public void reduce(){
        // 求出武力值的总和
        Integer sum = list.stream()
                .map(Hero::getStrength) //现获取武力值
                .reduce(0, Integer::sum); //求和
        System.out.println("武力值求和:" + sum);

        //求出武力值最大的对象
        Hero heroMax = list.stream()
                .reduce(new Hero("小趴菜", 0), (h1, h2) -> h1.getStrength() <= h2.getStrength() ? h2 : h1);
        System.out.println("武力值最大的:" + heroMax);

        //求出武力值最小的对象
        Hero heroMin = list.stream()
                .reduce(new Hero("无名", 10000), (h1, h2) -> h1.getStrength() <= h2.getStrength() ? h1 : h2);
        System.out.println("武力值最小的:" + heroMin);

        //求出英雄个数
        Integer count = list.stream().map(o -> 1).reduce(0, Integer::sum);
        System.out.println("英雄个数:" + count);

        System.out.println("==================简化====================");
        long count1 = list.stream().count();
        System.out.println("英雄个数:" + count1);

        Optional<Hero> max = list.stream().max(Comparator.comparing(Hero::getStrength));
        System.out.println("武力值最大的:" + max);

        Optional<Hero> min = list.stream().min(Comparator.comparing(Hero::getStrength).thenComparing(o -> o.getName().length()));
        System.out.println("武力值最小的且名字是最短的:" + min);
    }
}
